import ft from 'fourier-transform'
import db from 'decibels'
//傅里叶变换
export function fftTransform(waveform, isDb){
  // const ft = require('fourier-transform');
  // const db = require('decibels');
  if(isDb == null || isDb==undefined){
    isDb = false
  }
  //get normalized magnitudes for frequencies from 0 to 22050 with interval 44100/1024 ≈ 43Hz
  const spectrum = ft(waveform);
  if(!isDb){
    return spectrum
  }else{
    //convert to decibels
    const decibels = spectrum.map((value) => db.fromGain(value));
    return decibels
  }
}

// 小波变换
export function waveletTransform(inputSignal){
  const waveletCoefficients = []; // 存放小波系数的数组

  for (let i = 0; i < inputSignal.length; i++) {
    let coefficientSum = 0;

    // 根据小波函数的特性，将每个时间点上的值与相应位置的小波基函数乘起来并求和
    for (let j = 0; j <= Math.floor((i + 1) / 2); j++) {
      if ((j % 2 === 0 && i % 2 !== 0) || (j % 2 !== 0 && i % 2 === 0)) {
        coefficientSum += inputSignal[i] * (-Math.pow(-1, j));
      } else {
        coefficientSum += inputSignal[i] * Math.pow(-1, j);
      }
    }

    waveletCoefficients.push(coefficientSum);
  }
  return waveletCoefficients;
}


// 2的12次  不够补到4096，超过舍去
export function waveFFTSupply(waveList){
  const supplyLen = 4096
  const len = waveList.length
  let res = []
  if(len < supplyLen){
    res = waveList
    for(let i=0; i<supplyLen-len; i++ ){
      res.push(0)
    }
  }else if(len === supplyLen){
    res = waveList
  }else {
    res =  waveList.slice(0, supplyLen);
  }
  return res
}

